<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Profile extends Admin_Controller
{
	private $user_id = 0;
	private $rules = array (
						'name' => "required",
						'password' => "min_length[6]|max_length[20]",
						'confirm_password' => "matches[password]"
					);

	function __construct()
	{
		parent::Admin_Controller();
		//$this->setLogger('Users-Profile');

		$this->user_id = $this->session->userdata('user_id');
		$this->load->library('user_lib');

		$this->load->model('users_m');
		//$this->load->model('profile_m');

		$this->load->helper('user');

		$this->lang->load('user');
		//$this->lang->load('profile');
	}

    // USER PROFILE SECTION -------------------------------------------------------------------------------------

    // Show the current users profile
	function index()
	{
		if(!$this->data->user = $this->users_m->getUser(array('id'=>$this->user_id)) ):
			show_404();
		endif;
		$this->load->library ( 'validation' );

		// Shouldnt need to have done this, but if password exists make confirm_password required
		if ($this->input->post ( 'password' )) {
			$this->rules ['confirm_password'] .= '|required';
		}

		$this->validation->set_rules ( $this->rules );
		$this->validation->set_fields ();

		if ($this->validation->run ()) {
			$update_data ['name'] = $this->input->post ( 'name' );

			// Password provided, hash it for storage
			if ($this->input->post ( 'password' ) && $this->input->post ( 'confirm_password' )) {
				$this->load->helper ( 'security' );
				$update_data ['password'] = dohash ( $this->input->post ( 'password' ) . $this->data->user->salt );
			}

			if ($this->users_m->updateUser ( $this->user_id, $update_data )) {
				//$this->logger->info("Cap nhat user, id = ".$this->user_id, USER_ACTION_MANAGE_USERS);
				$this->session->set_flashdata ( 'success', $this->lang->line ( 'user_edit_success' ) );
			} else {
				//$this->logger->error("Cap nhat user, id = ".$this->user_id, USER_ACTION_MANAGE_USERS);
				$this->session->set_flashdata ( 'error', $this->lang->line ( 'user_edit_error' ) );
			}
			redirect('admin/users/profile');
		}else {
			$this->data->error_string = $this->validation->error_string;
		}

		// Override fields with provided values
		foreach ( array_keys ( $this->rules ) as $field ) {
			if (isset ( $_POST [$field] ))
				$this->data->user->$field = $this->validation->$field;
		}

		$this->data->toolbar = createToolbar( array(), array('label'=> 'Thông tin cá nhân [' . $this->data->user->name . ']', 'attribute' => 'class = "acc_per toolbar_title"'));

		$this->layout->create('profile/edit', $this->data);
	}
}
?>